package com.word.app.config.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

import org.apache.shiro.crypto.hash.SimpleHash;

@Slf4j
public class JWTUtil {

    private static final long EXPIRE_TIME = 86400L * 1000;

    public static String MD5(String password) {
		return new SimpleHash("md5", password,null,1).toHex();
	}
    
    // 判断token是否过期，过期时间一天
    public static boolean verify(String token) {
        try {
            String username = getUsername(token);
            Algorithm algorithm = Algorithm.HMAC256(MD5(username));
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username", username)
                    .build();
            verifier.verify(token);
            log.info("token is valid");
            return true;
        } catch (Exception e) {
            log.info("token is invalid{}", e.getMessage());
            return false;
        }
    }

    /**
     * 从 token中获取用户名
     *
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            log.error("error：{}", e.getMessage());
            return null;
        }
    }

    /**
     * 生成 token
     *
     * @param username 用户名
     * @param secret   用户的密码
     * @return token
     */
    public static String sign(String username) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(MD5(username));
            return JWT.create()
                      .withClaim("username", username)
                      .withExpiresAt(date)
                      .sign(algorithm);
        } catch (Exception e) {
            log.error("error：{}", e);
            return null;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        String token = sign("root");
        Thread.sleep(5000);
        System.out.println(verify(token));
    }
}
